package org.iori.util.text;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The util class to process properties file
 * 
 * @author zhang_jianbin
 * @history
 *         <p>
 *         2007-8-1 Created Zhang Jianbin
 * 
 */
public class PropertiesUtil {
	private static Log log = LogFactory.getLog(PropertiesUtil.class);

	/**
	 * Load data from properties file.
	 * 
	 * @param is
	 *            the input stream to read data
	 * @param encoding
	 *            the file encoding when reading
	 * @return all the properties
	 * @throws IOException
	 *             if error occurs
	 */
	public static Map loadProperties(InputStream is, String encoding)
			throws IOException {
		Map result = null;

		result = new HashMap(1000);
		Properties prop = new Properties();
		prop.load(is);
		is.close();

		Set col = prop.keySet();
		Iterator iter = col.iterator();
		while (iter.hasNext()) {
			String strKey = (String) iter.next();
			String value = (String) prop.get(strKey);
			if (encoding != null) {
				value = new String(value.getBytes("ISO-8859-1"), encoding);
			}
			result.put(strKey, value);

			if (log.isDebugEnabled()) {
				log.debug(strKey.toString() + " = " + value);
			}
		}

		return result;
	}

	/**
	 * Load data from properties file.
	 * 
	 * @param file
	 *            the file object to read data
	 * @param encoding
	 *            the file encoding when reading
	 * @return all the properties
	 * @throws IOException
	 *             if error occurs
	 */
	public static Map loadProperties(File file, String encoding)
			throws IOException {
		return loadProperties(new FileInputStream(file), encoding);
	}
}
